/*
 * @(#)ResourceCacheService.java
 * 2011-5-15 下午03:33:37
 *
 * Copyright (c) 2018-2028, HangZhou QiYun InfoTech Co.,Ltd. .
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.qyxx.platform.sysmng.accountmng.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.util.AntUrlPathMatcher;
import org.springframework.security.web.util.UrlMatcher;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.qyxx.platform.sysmng.accountmng.dao.AuthorityDao;
import com.qyxx.platform.sysmng.accountmng.dao.RoleDao;
import com.qyxx.platform.sysmng.accountmng.entity.Authority;
import com.qyxx.platform.sysmng.accountmng.entity.Role;
import com.qyxx.platform.sysmng.utils.Constants;


/**
 *  资源缓存
 *  @author gxj
 *  @version 1.0
 *  @since 1.6 2011-5-15 下午03:33:37
 */
@Component
@Lazy(false)
public class ResourceCacheService {
	
	private static final Logger logger = LoggerFactory.getLogger(ResourceCacheService.class);
	
	private ConcurrentMap<String, Collection<ConfigAttribute>> caMap;
	
	private ConcurrentMap<String, Authority> resourceMap;
	
	//private volatile boolean isLoaded = false; 
	
	private AccountManager accountManager;

	private UrlMatcher urlMatcher = new AntUrlPathMatcher();
	
	/**
	 * @param accountManager
	 */
	@Autowired
	public void setAccountManager(AccountManager accountManager) {
		this.accountManager = accountManager;
	}

	@PostConstruct
	public void init() {
		caMap = new ConcurrentHashMap<String, Collection<ConfigAttribute>>();
		//loadResource();
		resourceMap = new ConcurrentHashMap<String, Authority>();
		loadAllResource();
	}
	
	@PreDestroy 
	public void destory() { 
		caMap.clear();
		caMap = null;
		resourceMap.clear();
		resourceMap = null;
	}
	
	/**
	 * 加载资源缓存
	 */
	public void loadResource() {
		//通过数据库中的信息设置，resouce和role
		for (Role item:accountManager.getAllRoleWithLoadAuthority()){
			List<Authority> authorityList = item.getAuthorityList();
			//把资源放入到spring security的resouceMap中
			for(Authority au:authorityList){
				logger.info("获得角色：["+item.getRoleName()+"]拥有的acton有："+au.getResourceUrl());
				Collection<ConfigAttribute> attrs = caMap.get(au.getResourceUrl());
				if(attrs == null) {
					attrs = new ArrayList<ConfigAttribute>();
				}
				ConfigAttribute ca = new SecurityConfig(item.getId() + Constants.UNDERLINE + item.getRoleName());
				if(!attrs.contains(ca)) {
					attrs.add(ca);
				}
				caMap.put(au.getResourceUrl(), attrs);
			}
		}
		//isLoaded = true;
	}
	
	/**
	 * 加载所有资源
	 */
	public void loadAllResource() {
		ConcurrentMap<String, Collection<ConfigAttribute>> caMapNew = new ConcurrentHashMap<String, Collection<ConfigAttribute>>();
		ConcurrentMap<String, Authority> resourceMapNew = new ConcurrentHashMap<String, Authority>();
		List<Authority> authList = accountManager.getAllUsingAuthorityWithLoadRole();
		for(Authority auth : authList) {
			//if(Constants.IS_USING.equals(auth.getResourceStatus())) {
				//有效资源
				String url = auth.getResourceUrl();
				if(StringUtils.isNotBlank(url) 
						&& (Constants.RESOURCE_TYPE_MENU.equals(auth.getResourceType())
						|| Constants.RESOURCE_TYPE_BUTTON.equals(auth.getResourceType())
						|| Constants.RESOURCE_TYPE_FIELD.equals(auth.getResourceType()))) {
					resourceMapNew.put(url, auth);
					List<Role> roleList = auth.getRoleList();
					Collection<ConfigAttribute> attrs = new ArrayList<ConfigAttribute>();
					for(Role role : roleList) {
						if(Constants.IS_USING.equals(role.getRoleStatus())) {
							ConfigAttribute ca = new SecurityConfig(role.getId() + Constants.UNDERLINE + role.getRoleName());
							if(!attrs.contains(ca)) {
								attrs.add(ca);
							}
						}
					}
					caMapNew.put(url, attrs);
				}
			//}
		}
		this.caMap = caMapNew;
		this.resourceMap = resourceMapNew;
	}
	
	/**
	 * 刷新资源缓存
	 */
	public void refreshResource() {
		loadAllResource();
	}
	
	/**
	 * 获取资源MAP
	 * 
	 * @return
	 */
	public ConcurrentMap<String, Collection<ConfigAttribute>> getResourceCache() {
		/*if(!isLoaded) {
			loadResource();
		}*/
		return caMap;
	}

	/**
	 * 根据资源链接查询资源对象，记录日志时使用
	 * 
	 * @param url 资源链接
	 * @return
	 */
	public Authority getResourceByUrl(String url) {
		for(Map.Entry<String, Authority> en : resourceMap.entrySet()) {
			if(urlMatcher.pathMatchesUrl(en.getKey()+"*", url)) {
				return en.getValue();
			}
		}
		return null;
	}
	
}
